package com.zhan.easyexcelorder.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import com.zhan.easyexcelorder.model.SysUserExcelEntity;
import com.zhan.easyexcelorder.service.ExcelUser;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author zhan
 * @since 2019-12-06 8:58
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener<SysUserExcelEntity> {
    private List<SysUserExcelEntity> dataList = Lists.newArrayList();
    private ExcelUser excelUser;
    /**
     * 每隔50条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;

    public ExcelListener() {

    }

    public ExcelListener(List<SysUserExcelEntity> list) {
        this.dataList = list;
    }

    public ExcelListener(ExcelUser excelUser) {
        this.excelUser = excelUser;
    }

    /**
     * 通过 AnalysisContext 对象还可以获取当前 sheet，当前行【会循环遍历当前sheet的每一行】等数据
     */
    @Override
    public void invoke(SysUserExcelEntity excelEntity, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", excelEntity.toString());
        System.out.println("解析到一条数据:{ " + excelEntity.toString() + " }");
        dataList.add(excelEntity);

        if (dataList.size() > BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            dataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
        System.out.println("所有数据解析完成！");
    }

    private void saveData() {
        excelUser.saveData(dataList);
    }


    public List<SysUserExcelEntity> getDataList() {
        return dataList;
    }
}
